﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using AutoMapper;
using PublishNews.Entities;
using PublishNews.Models;
using PublishNews.Repositories;

namespace PublishNews.Controllers
{
    public class CategoryApiController : BaseApiController<Category, CategoryModel>
    {
        private ICategoryRepository categoryRepository;
        public CategoryApiController(ICategoryRepository repository)
            : base(repository)
        {
            categoryRepository = repository;
        }

        public override IHttpActionResult Get()
        {
            var entities = Repository.DbSet().OrderByDescending(x => x.UpdatedDate).ThenByDescending(x => x.CreatedDate);
            var model = Mapper.Map<IEnumerable<CategoryModel>>(entities);
            model = model.OrderBy(x => x.Name);
            return Ok(model);
        }

        public async Task<IHttpActionResult> GetAllCategories()
        {
            var entities = await categoryRepository.GetSubCategories(null);
            var categories = Mapper.Map<List<CategoryModel>>(entities);

            if (categories == null)
            {
                return NotFound();
            }
            else
            {
                categories = categories.OrderBy(x => x.Name).ToList();
                await GetSubcategories(categories);
            }

            return Ok(categories);
        }

        public async Task<IHttpActionResult> GetSubCategories(Guid? id)
        {
            var entities = await categoryRepository.GetSubCategories(id);
            var categories = Mapper.Map<List<CategoryModel>>(entities);
            if (categories == null)
            {
                return NotFound();
            }

            categories = categories.OrderBy(x => x.Name).ToList();
            return Ok(categories);
        }

        private async Task GetSubcategories(List<CategoryModel> categories)
        {
            foreach (var category in categories)
            {
                var entities = await categoryRepository.GetSubCategories(category.Id);
                if (entities.Any())
                {
                    var subCategories = Mapper.Map<List<CategoryModel>>(entities);
                    subCategories = subCategories.OrderBy(x => x.Name).ToList();

                    category.SubCategories = subCategories;
                    await GetSubcategories(subCategories);
                }
                else
                {
                    category.SubCategories = new List<CategoryModel>();
                }
            }
        }
    }
}

